简体   繁体   English

循环遍历数组并在Javascript中根据条件替换值

[英]Loop through array and replace value on condition in Javascript

My array and pseudo code are as follows.我的数组和伪代码如下。 I do need help with replacing values with stirng on condition.我确实需要帮助在条件下用搅拌替换值。 I tried below but can't move on.我在下面尝试过,但无法继续。

var = [5000, 2000, 4030, 1100];

for (var i = 0; i < arR.length; i++) {
    if (arR.includes >= 5000) {
        (‘senior’);
    } else if (arR.includes >= 2000) {
        console.log(‘mid’);
    } else {
        (‘junior’);
    }
}

Expected result: var = [senior, mid, mid, junior];预期结果: var = [senior, mid, mid, junior];

 let array = [5000, 2000, 4030, 1100]; let TransformedArray = array.map(item=>item>=5000 ? 'senior' : item>=2000 ? 'mid' : 'junior'); console.log(TransformedArray);

You can do that with Array.map() and use any conditional operator to filter the result im using ternary here.您可以使用 Array.map() 来做到这一点,并使用任何条件运算符在这里使用三元过滤结果。

 var someArray = [5000, 2000, 4030, 1100]; var anotherArray = someArray.map(function (rank) { return rank >= 5000 ? 'senior' : rank >= 2000 ? 'mid' : 'junior'; }); console.log(anotherArray);

if you need it this way for easy understanding of if else and for each如果您需要这种方式以便于理解 if else 和 for each

 var someArray = [5000, 2000, 4030, 1100]; var newArray = []; someArray.forEach(function (rank) { if (rank >= 5000) { newArray.push('senior'); } else if (rank >= 2000) { newArray.push('mid'); } else { newArray.push('junior'); } }); console.log(newArray);

var array = [5000, 2000, 4030, 1100];

function converter(item) {
  return item >= 5000 && 'senior' || item >= 2000 && 'mid' || item >= 0 && 'junior';
}

var newArray = array.map(converter)
console.log(newArray);

The function returns false if an element is not a number (or smaller than 0).如果元素不是数字(或小于 0),则该函数返回 false。 If you want to change that, you should cover the return with an if statement.如果你想改变它,你应该用 if 语句覆盖返回。

Just replace that element in the array, also iterate through the actual elements in your for-loop instead of checking if the value exists只需替换数组中的该元素,同时遍历 for 循环中的实际元素,而不是检查该值是否存在

var arR = [5000, 2000, 4030, 1100];

for (var i = 0; i < arR.length; i++) {
    if (arR[i] >= 5000) {
        arR[i] = "senior";
    } else if (arR[i] >= 2000) {
        arR[i] = "mid"
    } else {
        arR[i] = "junior"
    }
}

What I am doing here is checking each value, and if it satisfies a condition, then change it to the string it needs to be我在这里做的是检查每个值,如果它满足条件,则将其更改为它需要的字符串

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

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