Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/371.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何确定字符串是否包含字符并将值存储在两个单独的变量中_Javascript_Arrays_String_Substring - Fatal编程技术网

Javascript 如何确定字符串是否包含字符并将值存储在两个单独的变量中

Javascript 如何确定字符串是否包含字符并将值存储在两个单独的变量中,javascript,arrays,string,substring,Javascript,Arrays,String,Substring,我试图将一个字符串分成两个独立的变量。字符串存储在数组中并包含冒号。我希望冒号前的值是第一个变量,冒号后的值是第二个变量 我不知道如何做到这一点:目前,我已经完成了以下工作,但它只使用了substring方法 for(i = 0; i< productArray.length; i ++){ item = productArray[i]; stockCode = item.toString().substring(0, 1) console.log(stockCod

我试图将一个
字符串
分成两个独立的
变量
字符串
存储在数组中并包含冒号。我希望冒号前的值是第一个变量,冒号后的值是第二个变量

我不知道如何做到这一点:目前,我已经完成了以下工作,但它只使用了
substring
方法

for(i = 0; i< productArray.length; i ++){
    item = productArray[i];
    stockCode = item.toString().substring(0, 1)
    console.log(stockCode);
    quantity = item.toString().substring(3,5);
    console.log(quantity);
}
for(i=0;i
数组如下所示:
[“EXCEL 5LB黑色:2”、“EXCEL 5LB黑色:3”、“佐藤白色标签:2”、“佐藤墨水垫:1”、“佐藤枪:2”]

我想像这样存储这些值

  • var1=EXCEL 5LB黑色

  • var2=2

等等

var str = "How are you doing today?";
var res = str.split(" "); 
结果是
How,are,you,do,today?

你的情况:

for(i = 0; i< productArray.length; i ++){
    var item = productArray[i];
    var split = str.split(":");
    var item_name = split[0];
    var item_val = split[1];
}
for(i=0;i
您可以使用
拆分(“:”)拆分“:”上的字符串。

for(i=0;i
您应该尝试以下方法:

var str = "EXCEL 5LB BLACK:2";
var strArray[] = str.split(":");

strArray = [EXCEL 5LB BLACK, 2];
使用
项。拆分(“:”)
。它将返回一个数组,其中包含您需要的两个值。

您可以按如下方式选择数组中的每个元素:

var newArray = [];
for(var key in productArray){//foreach element in array
   newArray.push(productArray[key].split(':')); //split by ":" and push into new newArray
}
console.log(newArray); //output could be [["EXCEL 5LB BLACK","2"],[...]]
使用

for(变量i=0;i
for(var i = 0; i< ar.length; i ++){
    temp = ar[i].split(':');

    console.log('first='+temp[0]+' second='+temp[1])
}
var productArray = ["EXCEL 5LB BLACK:2", "EXCEL 5LB BLACK:3", "SATO WHITE LABEL:2", "SATO INK PADS:1", "SATO GUN:2"];
var colorArray = new Array();
var numberArray = new Array();

for(i = 0; i< productArray.length; i ++){
    var item = productArray[i];
    var itemArray = [];
    itemArray = item.split(":")

    colorArray.push (itemArray[0]);
    numberArray.push (itemArray[1]);
console.log(colorArray);
console.log(numberArray);