在Javascript中,有没有办法从数组中选择包含某些内容的单词。例如,["swimming", "basketball", "chess", "rowing"]
,我想只选择包含“-ing”的项目并将字符串应用于它们。
“我去”+“游泳”,等等。
反过来,有没有办法选择不包含该参数的项目。没有“-ing”的单词
“我玩”+“篮球”,等等
答案 0 :(得分:3)
您可以使用:
let arr = ["swimming", "basketball", "chess", "rowing"];
let result = arr.map(s => (s.includes("ing")? "I go ": "I play ") + s);
console.log(result);
或者,您可以使用Array.prototype.filter()
过滤此数组,并在每个阵列上执行您想要的任何操作。
let arr = ["swimming", "basketball", "chess", "rowing"];
let strWithIng = arr.filter(s => s.includes("ing"));
let strWithoutIng = arr.filter(s => !s.includes("ing"));
console.log(strWithIng);
console.log(strWithoutIng);
答案 1 :(得分:1)
一种方法 -
var arr = ["swimming", "basketball", "chess", "rowing"];
arr.map(i=>i.indexOf("ing") != -1? console.log("I go "+ i):console.log("I play "+ i));
var res = arr.map(i=>(i.indexOf("ing") != -1?"I go " :"I play ")+ i); //if you want to put in array
console.log(res);