gpt4 book ai didi

javascript - 将两个字符串分隔为两个变量

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:07:31 24 4
gpt4 key购买 nike

假设我有这个:

var colors = 'Red,Blue,Green,Orange,White,Brown';

我试图解析它以获得所有颜色,这意味着:

color1='Red';
color2='Blue';
[...]

我曾经使用 matches() 然后放一个逗号,因为颜色是用逗号分隔的,所以我放了 ',',但结果不是我所期望的...有什么快速的方法吗?

最佳答案

Is there any fast way to do it?

是的,我推荐你使用split()

正如文档所说:

The split() method is used to split a string into an array of substrings, and returns the new array.

Tip: If an empty string ("") is used as the separator, the string is split between each character.

Note: The split() method does not change the original string.

所以你可以做这样的事情来获得相同的颜色:

var colors = 'Red,Blue,Green,Orange,White,Brown'.split(','); //use .split() to split the character you want to.
var color1 = colors[0];
var color2 = colors[1];
var color3 = colors[2];
[...]
alert("Color 1 = " +color1 + "\n"+ "Color 2 = " + color2);

现在您可以执行一些逻辑来了解您的 var colors 或任何您想要的项目。

希望对您有所帮助。

关于javascript - 将两个字符串分隔为两个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33567409/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com