简体   繁体   English

从数组中提取值

[英]Extract values from array

Hello my script watches a stream...您好,我的脚本观看 stream ......

On a message it will extract some data for me using a variable.在一条消息中,它将使用变量为我提取一些数据。

Here's the script:这是脚本:

  var evtSource = new EventSource("http://URL.com/_watch//_index?_=1557958948927");

evtSource.onmessage = function(e) {
var obj = JSON.parse(e.data);
var lineString = JSON.stringify(obj.line)
var size = JSON.stringify(obj.lineWidth)
var color = JSON.stringify(obj.lineColor) // Not needed, but defined anyways.
var chat = JSON.stringify(obj.msg)
var line = obj.line
console.log(line)

line.forEach(function(point, index){
     console.log(JSON.stringify(point)); // console log example// -> "[120,250]"
  });
}

in google's console it logs something like this [120,250]在谷歌的控制台中,它记录了这样的内容 [120,250]

How could I get each number, like the 120 as a variable, and the 250 as a different variable?我怎样才能得到每个数字,比如 120 作为变量,而 250 作为不同的变量?

I tried something with the substr() method but it didn't work.我尝试了 substr() 方法,但没有奏效。 It would somehow get the comma.它会以某种方式得到逗号。

Just don't stringify the point array.只是不要对point组进行字符串化。 Without stringifying you can destructure the array, like this:如果不进行字符串化,您可以解构数组,如下所示:

const [x, y] = point;

or in a traditional way:或以传统方式:

const x = point[0];
const y = point[1];

both solutions are equal and produce the same output.两种解决方案都是相同的,并且产生相同的 output。 Example:例子:

 const point = [120, 250]; const [x, y] = point; console.log(`x: ${x}, y: ${y}`);

So your .forEach() could look like this:所以你的.forEach()可能看起来像这样:

line.forEach(function(point, index){
    const [x, y] = point;
    console.log(x, y); // console log example// -> "120 250"
});

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

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