题解 | FED57 #移除数组中的元素#
移除数组中的元素
https://www.nowcoder.com/practice/edbc7496a36e433c89d298b9256af856
描述
移除数组 arr 中的所有值与 item 相等的元素。不要直接修改数组 arr,结果返回新的数组
示例1
输入:
[1, 2, 3, 4, 2], 2复制
输出:
[1, 3, 4]
解
function remove(arr, item) {
/*法一:JS中的filter():
array.filter(function(curentValue[,index,arr){},thisValue])
返回新数组,包含符合条件的所有元素,没有符合条件的则返回空数组
filter()和forEach()的区别:filter()有返回值 返回新数组,包含符合条件的元素;
forEach()不产生新数组,返回undefined
相同点:
map()、filter()、forEach()的参数都是 当前元素、当前元素的索引、当前元素所属的数组,
匿名函数中的this都是指向window
参考:https://www.csdn.net/tags/MtTaMg3sMTg1MDYxLWJsb2cO0O0O.html https://baijiahao.baidu.com/s?id=1719633936157373069&wfr=spider&for=pc https://www.jb51.net/article/213663.htm https://m.runoob.com/jsref/jsref-foreach.html*/
return arr.filter(i=>{
return i!=item;
});
/*法二:forEach()*/
var a=[];
arr.forEach(i=>{
if(i!=item){
a.push(i);
}
});
return a;
}
查看2道真题和解析