javascript - 询问数组javascript中的if条件

标签 javascript arrays

我有这样的数组结构:

array[1].name = "parameter-name";
array[1].value = null;
array[2].name = null;
array[2].value = "parameter-value2";

我想将 null 更改为 ""

这是我在ajax中显示的方式:

for (var i in array) {

    if(array[i].name == null) {
            array[i].name = "";
    } 
    if(array[i].value == null) {
            array[i].value = ""; 
    }
}

如何对数组的所有项目进行 if 条件?

for (var i in array) {

    if(array[i] == null) {
        array[i] = "";
    } 

}

我尝试了这个,但结果是 JavaScript 错误。

最佳答案

array.map(({name, value}) => ({
   name : (name === null) ? "" : name,
   value : (value === null) ? "" : value    
}))

假设您正在使用 null 完全检查相等性(不是 undefinedfalse 或其他内容),这就是我们使用 的原因x === null 而不是 !x

const array = [
  {name: "Something", value: null},
  {name: "SomethingB", value: "ValB"},
  {name: null, value: "ValC"},
]
   
 console.log(  
    array.map(({name, value}) => ({
       name : (name === null) ? "" : name,
       value : (value === null) ? "" : value    
    }))
    
)

关于javascript - 询问数组javascript中的if条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42335771/

相关文章:

javascript - MouseOut/MouseLeave - 下拉菜单上的事件触发器

c - 如何将空白数组排序到顶部以便我可以删除它们

javascript - 重新索引数组

javascript - 单击后按钮属性恢复正常

C - fopen() 的相对路径

php - 将具有相同键的键值对添加到数组中

c++ - 整数数组与 C++ 中的整数指针

javascript - 这个 Redux (react) 应用程序可能存在什么问题?

javascript - 如何在 Angular 中创建多个单选组

javascript - 在javascript中以毫秒为单位获取当前的unix时间