freecodecamp.cn icon indicating copy to clipboard operation
freecodecamp.cn copied to clipboard

[266]Seek and Destroy的问题

Open Sagitarioo opened this issue 10 years ago • 3 comments

Challenge Seek and Destroy has an issue. User Agent is: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36. Please describe how to reproduce this issue, and include links to screenshots if possible.

My code:

function destroyer(arr) {
  var arrt=new Array();
  var attt=arr.slice(1,arr.length);
  for(i=0;i<arr[0].length;i++){
     if(attt.indexOf(arr[0][i])<0){
        arrt.push(arr[0][i]);
      }
   }
  return arrt;
}

destroyer([[1, 2, 3, 1, 2, 3], 2, 3]);

通过在JS Bin中测试,我的函数是达到这个功能的。这个题目中,arr=[1, 2, 3, 1, 2, 3], 2, 3的这种定义有问题,这既不是一个字符串,也不是一个数组。题目本来想的定义arr应该是个数组,应该定义为arr=[[1, 2, 3, 1, 2, 3], 2, 3],即一个二维数组,所以题目里的测试也应该再加上一组[ ].

我的E-mail为:[email protected]

Sagitarioo avatar Oct 15 '16 09:10 Sagitarioo

不好意思,这个怪我们的翻译不到位,题目原文为:

You will be provided with an initial array (the first argument in the destroyer function), followed by one or more arguments. Remove all elements from the initial array that are of the same value as these arguments.

也就是说这个方法传入的参数个数是不固定的,第一个参数是一个待操作的数组,之后的每个参数是需要你在这个数组中删除的与之相等的值。这么说很绕,举个例子:

destroyer([1, 2, 3, 1, 2, 3], 2, 3)

的意思就是删除[1, 2, 3, 1, 2, 3]里面的所有2和3。

discountry avatar Oct 16 '16 15:10 discountry

image @Sagitarioo 函数的形参arr并不等于我们实际传输的参数,只有arguments才等于实参。 此处的形参arr仅仅是实参的第一个参数,即数组。 上图来自javascript面向对象精要2.3节,希望对你有帮助。 课程中有提示文档:arguments, 所以很显然此题需要用到arguments来获取到实参,并把arguments对象转化为数组。

var args = Array.from(arguments);  // es6 写法
var args = Array.prototype.slice.call(arguments); // es3写法
var args = [].slice.call(arguments); // es3写法简写

如果还是不理解请参考MDN:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/slice#Array-like

如果想了解更多解法可以参考Wiki:https://github.com/huluoyang/freecodecamp.cn/wiki/seek-and-destroy

huluoyang avatar Oct 19 '16 07:10 huluoyang

非常感谢。这题目的关键在于函数的参数被自动保存在arguments数组中,因此参数的数量可变就不成问题了。 如果这个点不知道,什么算法都是白搭。

cxmSevenlaps avatar Nov 14 '16 07:11 cxmSevenlaps