我正在使用Google Apps脚本编写一个用于表的脚本,并且我将数组作为参数传递到一个函数中,我想对内部的数组进行排序,返回一个新阵列,该阵列被分类后也经过了一些操纵。我从这里的另一个线程
拿了一些代码代码:
function removeDupes(array) {
var outArray = [];
array.sort(); //sort incoming array according to Unicode
outArray.push(array[0]); //first one auto goes into new array
for(var n in array){ //for each subsequent value:
if(outArray[outArray.length-1]!=array[n]){ //if the latest value in the new array does not equal this one we're considering, add this new one. Since the sort() method ensures all duplicates will be adjacent. V important! or else would only test if latestly added value equals it.
outArray.push(array[n]); //add this value to the array. else, continue.
}
}
return outArray;
}
array.sort();
返回错误
'TypeError:无法调用方法" sort"不确定的。(第91行,文件&quot"代码")&quot
。我如何在将该函数传递到该函数的数组上执行sort()方法?
错误非常明显,无论您用来调用removeDupes
的代码如何传递实际数组,否则.sort()
方法将在传入的参数上使用。[旁注:如果您有兴趣删除重复项,为什么需要对数组进行排序?]
除此之外, Array.filter()
方法可以过滤重复项,而无需进行所有循环。而且,即使您确实循环一个数组,也不应使用for/in
循环,因为它们是用于用字符串钥匙名而不是数组的对象进行枚举。数组循环应使用常规计数循环,.forEach()
或许多自定义 Array.prototype
循环方法之一。
var testArray = ["apple", "bannana", "orange", "apple", "orange"];
function removeDupes(arr){
// The .filter method iterates all of the array items and invokes a
// callback function on each iteration. The callback function itself
// is automatically passed a reference to the current array item being
// enumerated, the index of that item in the array and a reference to
// the array being iterated. A new array is returned from filter that
// contains whatever the callback function returns.
return arr.filter( function( item, index, inputArray ) {
// If the index of the item currently being enumerated is the same
// as the index of the first occurence of the item in the array, return
// the item. If not, don't.
return inputArray.indexOf(item) == index;
});
}
var filteredArray = removeDupes(testArray);
console.log(filteredArray);