如何从一长串数据中获取数据?

时间:2018-06-28 08:28:15

标签: javascript arrays string

我下面有一个非常大的数据数组,称为Data_Array。如何仅获得数据的第五和第六索引?以一种自动的方式。

var Data_Array = ["BETA 135 MEMB 3 6",
              "MATERIAL STEELAPPROX ALL",
              "SUPPORTS",
              "5 13 16 22 24 PINNED",
              "20 FIXED",
              "7 FIXED BUT FX KFY 200",
              "9 FIXED BUT FZ MX KFY 150 KMZ 200",
              "LOAD 1 LOADTYPE Dead  TITLE DEAD",
              "SELFWEIGHT Y -1",
              "LOAD 2 LOADTYPE Live  TITLE LIVE"]

我正在努力实现以下价值:

["7 FIXED BUT FX KFY 200",
 "9 FIXED BUT FZ MX KFY 150 KMZ 200"]

我正在尝试创建一个代码,在该代码中它计算所有数组,然后在检测到单词FIXED时停止。然后从那里将返回其array.length然后(这将是第一个索引)。然后计数直到Load(这将是第二个索引)。因此,代码

function countIndex(array, str1, str2){

  count until Fixed then = gives 5
  count until Load then = give 7

}

Array.splice(1st_index,2nd_index);

我实际上有执行此操作的代码,但是它无法检测到不在元素的第一个索引中的字符串。现在,字符串“ FIXED”不在第一个索引中,它将不起作用。仅当str1和str2值是数组中元素的第一个索引时才有效。

function pullAllDataBetween(data, str1, str2) {

  var string_nodes = [];
  var append = false;

  for (var i = 0; i < data.length; i++) {
   if (data[i] === str1) {
      append = true;
      continue;
   } else if (data[i] === str2) {
      append = false;
      break;
   }

      if (append) {
     string_nodes.push(data[i]);
   }
  }

    return string_nodes;
  }

1 个答案:

答案 0 :(得分:0)

console.log(Data_Array.slice(5, 7)); 

输出:

[ '7 FIXED BUT FX KFY 200',
  '9 FIXED BUT FZ MX KFY 150 KMZ 200' ]

var Data_Array = ["BETA 135 MEMB 3 6",
          "MATERIAL STEELAPPROX ALL",
          "SUPPORTS",
          "5 13 16 22 24 PINNED",
          "20 FIXED",
          "7 FIXED BUT FX KFY 200",
          "9 FIXED BUT FZ MX KFY 150 KMZ 200",
          "LOAD 1 LOADTYPE Dead  TITLE DEAD",
          "SELFWEIGHT Y -1",
          "LOAD 2 LOADTYPE Live  TITLE LIVE"];

console.log(Data_Array.slice(5, 7)); 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

仅获取包含the word FIXED的那些字符串的数组并获取其长度:

var Data_Array = ["BETA 135 MEMB 3 6",
          "MATERIAL STEELAPPROX ALL",
          "SUPPORTS",
          "5 13 16 22 24 PINNED",
          "20 FIXED",
          "7 FIXED BUT FX KFY 200",
          "9 FIXED BUT FZ MX KFY 150 KMZ 200",
          "LOAD 1 LOADTYPE Dead  TITLE DEAD",
          "SELFWEIGHT Y -1",
          "LOAD 2 LOADTYPE Live  TITLE LIVE"];


var arr = Data_Array.filter(line => /FIXED/.test(line));

console.log(arr);

console.log(arr.length);

function count(arr, str){
  for(var i = 0; i<arr.length;i++){
    if(arr[i].indexOf(str)!==-1)
      return i;
  }
}

console.log(count(Data_Array, "FIXED"));

console.log(count(Data_Array, "LOAD"));