Javascript 丢弃数组中的元素,拼接就是答案吗? /* ***如果所有元素都匹配,它应该返回一个空数组。 ***如果传入一个空数组,它应该返回一个空数组 数组。 */ 函数removeElement(数组、丢弃器){ if(array.length==0){ 数组=[]; } 对于(var i=0;i[1,3,1]
有人知道如何删除在discarder参数中指定的数组元素吗 另外,如果所有元素都相同,我需要返回一个空数组。我在这个问题上坚持太久了。试试这个:Javascript 丢弃数组中的元素,拼接就是答案吗? /* ***如果所有元素都匹配,它应该返回一个空数组。 ***如果传入一个空数组,它应该返回一个空数组 数组。 */ 函数removeElement(数组、丢弃器){ if(array.length==0){ 数组=[]; } 对于(var i=0;i[1,3,1],javascript,Javascript,有人知道如何删除在discarder参数中指定的数组元素吗 另外,如果所有元素都相同,我需要返回一个空数组。我在这个问题上坚持太久了。试试这个: /* ***If all the elements match, it should return an empty array. ***If an empty array is passed in, it should return an empty array. */ function removeElement(array, dis
/*
***If all the elements match, it should return an empty array.
***If an empty array is passed in, it should return an empty
array.
*/
function removeElement(array, discarder) {
if(array.length === 0) {
array = [];
}
for(var i=0; i<array.length; i++) {
if(discarder === array[i]) {
array.splice(i, 1);
}
return array;
}
}
var output = removeElement([1, 2, 3, 2, 1], 2);
console.log(output); // --> [1, 3, 1]
试试这个:
/*
***If all the elements match, it should return an empty array.
***If an empty array is passed in, it should return an empty
array.
*/
function removeElement(array, discarder) {
if(array.length === 0) {
array = [];
}
for(var i=0; i<array.length; i++) {
if(discarder === array[i]) {
array.splice(i, 1);
}
return array;
}
}
var output = removeElement([1, 2, 3, 2, 1], 2);
console.log(output); // --> [1, 3, 1]
你需要使用
constremoveelement=(数组,丢弃器)=>array.filter(value=>value!==discarder);
var输出=移除元素([1,2,3,2,1],2);
console.log(输出);
您需要使用
constremoveelement=(数组,丢弃器)=>array.filter(value=>value!==discarder);
var输出=移除元素([1,2,3,2,1],2);
console.log(输出);
使用拼接,这将起作用:
函数removeItemFirst(arr,值){
var指数=arr.indexOf(值);
如果(索引>-1){
阵列拼接(索引1);
}
返回arr;
}
函数removeItemAll(arr,值){
var i=0;
而(i
但更好的方法是使用@Shuvo的答案中提到的
.filter()
。使用拼接,这将起作用:
函数removeItemFirst(arr,值){
var指数=arr.indexOf(值);
如果(索引>-1){
阵列拼接(索引1);
}
返回arr;
}
函数removeItemAll(arr,值){
var i=0;
而(i
但更好的方法是使用@Shuvo的答案中提到的.filter()
。- 使用。无需其他检查
- 此外,还可以使函数接受多个丢弃器并使用
const removeElement=(arr,…rem)=>arr.filter(x=>!rem.includes(x));
console.log(removelement([],2));//[]
log(removelement([1,2,3,2,1,2]);//[1,3,1]
log(removeElement([1,2,3,2,1],2,3));//[1,1]
log(removeElement([1,2,3,2,1],2,3,1));//[]
- 使用。无需其他检查
- 此外,还可以使函数接受多个丢弃器并使用
const removeElement=(arr,…rem)=>arr.filter(x=>!rem.includes(x));
console.log(removelement([],2));//[]
log(removelement([1,2,3,2,1,2]);//[1,3,1]
log(removeElement([1,2,3,2,1],2,3));//[1,1]
console.log(removeElement([1,2,3,2,1],2,3,1));//[]
return array.filter(item=>item!==discarder)return array.filter(item=>item!==discarder)