简体   繁体   English

用JavaScript获取输入数组键值的最佳方法

[英]Best way to get input array key value with javascript

I've got the following code to get the value of input name array key with javascript: 我有以下代码来使用javascript获取输入名称数组键的值:

 var input = document.querySelector('input'); var value = input.name.match(/\\[(.*?)\\]/)[1]; console.log(value); 
 <input type="text" name="hello[101][]" /> 

Now this works fine. 现在可以正常工作了。

But I am wondering if there is a better way then ...name.match(/\\[(.*?)\\]/)[1]; 但是我想知道是否有比...name.match(/\\[(.*?)\\]/)[1];更好的方法...name.match(/\\[(.*?)\\]/)[1]; to get the input name array key value(s) ? 获取input name array key value(s) Like is there a way to convert the hello[101][] string to a kind of javascript array or object? 就像有一种方法可以将hello[101][]字符串转换为一种javascript数组或对象吗? Like what if I want to get all keys from: 就像如果我想从中获取所有密钥怎么办:

<input type="text" name="hello['one'][101]['test'][]" />

Here is an eval example 这是一个评估示例

 var str = "hello['one'][101]['test'][]", parts=eval(str.substring(str.indexOf("[")).split("][").join(",")) console.log(parts) 

You can pass a regular expression to split() method to make an array for you. 您可以将正则表达式传递给split()方法为您创建一个数组。 It can be done pretty much the same way. 几乎可以用相同的方式完成。

var arrayOfIntputValues = input.name.split(/\[(.*?)\]/)

But it will return ["hello", "'one'", "", "101", "", "'test'", "", "", ""] so you have to delete empty elements. 但是它将返回["hello", "'one'", "", "101", "", "'test'", "", "", ""]因此您必须删除空元素。

arrayOfInputVaules.filter(function(x){return x!=''})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM