简体   繁体   English

Javascript 过滤器 function,行为不符合预期

[英]Javascript Filter function, not behaving as expected

My code is very simple: I'm using the filter to modify one element of the array.我的代码很简单:我使用过滤器来修改数组的一个元素。 I checked that the if state does hit and "sattar" is returned.我检查了 if state 确实命中并返回了“sattar”。 However, both arrays: person and new_p print: orignal [ 'ali', 'hassan', 'ameer' ] changed [ 'ali', 'hassan', 'ameer' ]然而,arrays: person 和 new_p print: orignal [ 'ali', 'hassan', 'ameer' ] 都改变了 [ 'ali', 'hassan', 'ameer' ]

What am I missing here?我在这里想念什么?

 const person = ["ali", "hassan", "ameer"]; const new_p = person.filter(p => { if (p === "hassan") { return "sattar" } return p }) console.log("orignal", person); console.log("changed", new_p);

Use .map instead:使用.map代替:

 const person = ["ali", "hassan", "ameer"]; const new_p = person.map(p => { if (p === "hassan") { return "sattar" } return p }) console.log("orignal", person); console.log("changed", new_p);

A shorter version:一个较短的版本:

 const person = ["ali", "hassan", "ameer"]; const new_p = person.map(p => p === "hassan"? "sattar": p); console.log("orignal", person); console.log("changed", new_p);

use .map instead .filter使用.map代替.filter

const person = ["ali", "hassan", "ameer"];
const new_p = person.map((p) => {
   if (p == "hassan") {
      return "sattar";
   }
   return p;
})

console.log("orignal", person);
console.log("changed", new_p);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM