我找到了几种方法来从数组中删除一组值,然后更改数组中的值(或以相反的顺序)。例如:
original_array= ["unwanted variable 1","Score: Question 1","Score: Question 2","Score: Question 3","unwanted variable 2"];
// i want to end with just the "Score:" variables.
// method 1
scales = original_array.filter(function(element){
if(element.indexOf("Score:") !== -1){
return element.replace("Score: ","");
}
});
我希望这既能将数组减少到相关变量,又能将“分数:”替换为空。它减少了数组,但不改变变量的值。
我还尝试过使用 .map 而不是 .filter。
//method 2
scales = original_array.map(function(element){
if(element.indexOf("Score:") !== -1){
return element.replace("Score: ","");
}
});
它将所有无效变量替换为“未定义”,但确实更改了有效变量的值(例如“问题 1”而不是“分数:问题 1”。
有没有一种优雅的方法可以使用这两个函数来过滤并重命名变量?或者我必须分两步完成?
最佳答案
在写问题时,我发现你可以组合 .map 和 .filter:
scales = original_array.filter(function(element){
if(element.indexOf("Score:") !== -1){
return element;
}
}).map(function(element){
return element.replace("Score: ","");
});
但是 - 我希望有一个比这更简单或更优雅的解决方案。
关于javascript - 在 javascript 中获得映射和过滤器的好处的最优雅的方法是减少数组并更改其中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46543199/