简体   繁体   English

如何直接访问(javascript)拆分值?

[英]How to directly access (javascript) split values?

Is there any way to access split values without putting them into separate value? 有什么方法可以在不将拆分值放入单独值的情况下对其进行访问?

var content = "some|content|of"; 

var temp = content.split("|");   
var iwilluseit = "something" + temp[1] + temp[2]

How to do this w/o temp variable ?? 如何不使用temp变量? (inline in setting of iwilluseit var) (内联iwilluseit var的设置)

It's incredibly inefficient, but you could call split multiple times: 它效率极低,但是您可以多次调用split:

var iwilluseit = 'something' + content.split('|')[1] + content.split('|')[2];

There's also the slice() + join() option: 还有slice()+ join()选项:

var iwilluseit = 'something' + content.split('|').slice(1,2).join('');

Really, though, just creating the temp variable is the best way to go. 但是,实际上,仅创建temp变量是最好的方法。

content.split("|").slice(1,3).join("")

No, you need to assign the result of Array.split() to an intermediate variable before it can be used, unless you don't mind the performance hit of calling Array.split() for each value you want to grab. 不,您需要将Array.split()的结果分配给中间变量,然后才能使用它,除非您不介意为每个要获取的值调用Array.split()会对性能造成影响。

You could patch String.protoype to add a method that would take an array of strings and substitute it into a string. 您可以修补String.protoype以添加一个方法,该方法将使用字符串数组并将其替换为字符串。

怎么样:

var iwilluseit = "something" + content.split("|").slice(1,3).join(""));

You can also do: 您也可以:

var iwilluseit = "something" + content.substr( content.indexOf( "|" ) ).split("|").join("");

Of course, this will only work if you are simply trying to remove the first value. 当然,这仅在您只是尝试删除第一个值时才有效。

More importantly: Why do you need it to be in line? 更重要的是:为什么需要排队?

If the purpose of not assigning it to a variable is to be able to do this in a context where you can only have one Javascript expression, you could also use a closure, and assign it to the variable in it: 如果不将其分配给变量的目的是能够在只能有一个Javascript表达式的上下文中执行此操作,则也可以使用闭包,并将其分配给其中的变量:

(function() { var temp = content.split("|"); return "something" + temp[1] + temp[2]; })()

Which would be usable in an expression context, and not have the performance hit. 这将在表达式上下文中可用,而不会影响性能。

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

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