[英]Covert comma-separated string to array
嘗試將逗號分隔的字符串轉換為帶引號的數組,並在js中將每個值引起來:
var ipd = 'field1,field2'; console.log('Img Pad string: ' + ipd); // field1,field2 var ipdarray = new Array(); ipdarray = ipd.split(','); console.log('Img Pad array split: ' + typeof ipdarray); // object console.log('Img Pad array: ' + ipdarray); // field1,field2
我希望數組為:[“ field1”,“ field2”]
嘗試遵循以下步驟: 將逗號分隔的字符串轉換為數組 ,但未轉換為數組。
它正在轉換為數組,但是當您輸出字符串(在console.log中)時,由於使用+運算符(充當串聯器),該數組被強制轉換回該字符串語法。
這是正在發生的事情的更孤立的示例:
var string = 'field1,field2'; var arr = string.split(','); console.log(Array.isArray(arr)); console.log(arr.length); //When using the +, it will coerce into a string console.log('Coerce to string ' + arr); //When passing the array as an argument, it will stay an array console.log('Stays and array', arr);
為了保留數組文字語法,如果要使用+運算符,則需要在輸出之前對其進行JSON.stringify數組,或者可以將數組作為單獨的參數輸出到console.log。
JSON.stringify(ipdarray);
實際觀看:
var ipd = 'field1,field2'; console.log('Img Pad string: ' + ipd); // field1,field2 var ipdarray = new Array(); ipdarray = ipd.split(','); console.log('Img Pad array split: ' + typeof ipdarray); // object console.log('Img Pad array: ' + JSON.stringify(ipdarray)); // ["field1","field2"] // OR console.log('Img Pad array: ', ipdarray); // ["field1","field2"]
同樣,數組是“對象”,但是還有其他方法可以確定“對象”是否是數組的實例:
var arr = []; console.log(typeof arr); console.log(arr instanceof Array) console.log(Array.isArray(arr));
給定輸入字符串,您可以將String.prototype.match()
與RegExp
/[^,]+/g
配合使用/[^,]+/g
以匹配一個或多個非逗號字符,
var ipd = 'field1,field2';
var ipdarray = ipd.match(/[^,]+/g);
注意, +
運算符將數組轉換為字符串
console.log('Img Pad array: ' + ipdarray); // field1,field2
在console.log()
調用中使用逗號,
運算符
console.log('Img Pad array: ', ipdarray); // field1,field2
var a = "field1,field2" var b = a.split(','); var c = b.map(function (v) { return '"' + v + '"'; }) console.log(c); console.log(c[0]); console.log(c[1]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.