javascript 我可以在 .split() 之后直接访问数组的第二个值吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7390091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I access directly to the second value of an array after .split()?
提问by markzzz
I have this code :
我有这个代码:
var tmp=$(this).attr('id').split("_");
and I'd like to store on tmp the second value after the split. So if $(this).attr('id') = "hello_marco" I'd like to store in tmp the value marco, not the array.
我想在 tmp 上存储拆分后的第二个值。因此,如果 $(this).attr('id') = "hello_marco" 我想在 tmp 中存储值 marco,而不是数组。
Of course, I want to do it directly in one line of code, without first store the array and the access to it with array[1].
当然,我想直接在一行代码中完成,而不是先存储数组并使用array[1] 访问它。
Is it possible on JS/Jquery?
在 JS/Jquery 上有可能吗?
回答by dertkw
var tmp = $(this).attr('id').split("_")[1];
回答by Marc B
var tmp = $(this).attr('id').split('_')[1];
// ^^^
Split returns an array, so just dereference the array.
拆分返回一个数组,因此只需取消引用该数组。
回答by Voooza
Just add it to the end
把它加到最后
var tmp=$(this).attr('id').split("_")[1];
it's not probably best practice but it works
这可能不是最佳实践,但它有效
回答by genesis
var tmp = $(this).attr('id').split("_")[1];