如何用Javascript替换数组中的项? [英] How to replace an item in an array with Javascript?

查看:206
本文介绍了如何用Javascript替换数组中的项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此数组的每个项目都是一些数字。

Each item of this array is some number.

var items = Array(523,3452,334,31, ...5346);

如何使用新数字替换数组中的某些数字?

How do I replace some number in with array with a new one?

例如,我们想用1010替换3452,我们该如何做?

For example, we want to replace 3452 with 1010, how would we do this?

推荐答案

var index = items.indexOf(3452);

if (index !== -1) {
    items[index] = 1010;
}

此外,建议您不要使用构造函数方法初始化数组。相反,请使用文字语法:

Also it is recommend you not use the constructor method to initialize your arrays. Instead, use the literal syntax:

var items = [523, 3452, 334, 31, 5346];

您还可以使用运算符你是简洁的JavaScript并希望缩短 -1 比较:

You can also use the ~ operator if you are into terse JavaScript and want to shorten the -1 comparison:

var index = items.indexOf(3452);

if (~index) {
    items[index] = 1010;
}

有时我甚至想写一个包含用于抽象此检查的功能,以便更容易理解正在发生的事情。这对数组和字符串都很有用:

Sometimes I even like to write a contains function to abstract this check and make it easier to understand what's going on. What's awesome is this works on arrays and strings both:

var contains = function (haystack, needle) {
    return !!~haystack.indexOf(needle);
};

// can be used like so now:
if (contains(items, 3452)) {
    // do something else...
}

从字符串的ES6 / ES2015开始,为阵列的ES2016提议,您可以更轻松地确定是否有源包含另一个值:

Starting with ES6/ES2015 for strings, and proposed for ES2016 for arrays, you can more easily determine if a source contains another value:

if (haystack.includes(needle)) {
    // do your thing
}

这篇关于如何用Javascript替换数组中的项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆