您的位置:首页技术文章
文章详情页

javascript - 怎么操作数组去分割冒号取出对应的值。

【字号: 日期:2024-03-04 08:08:31浏览:26作者:猪猪

问题描述

['1001001:95', '1001002:100', '1001003:35', '1001004:37.5', '1001005:60', '1001006:100', '1001007:90', '1001008:140', '1001009:60', '1001010:90']

怎么去优雅的操作数组,取出冒号前后的数字并匹配在一起?不好意思,没表述清楚;我需要获取到冒号后面的数字,我整体了一下思路。

if(1001001) { var value == 95}

问题解答

回答1:

var obj = {};arr.forEach(function(item) { item = item.split(’:’) obj[item[0]] = item[1];});回答2:

按照你的if语句来说,如果你单纯的想根据冒号前边的id数字得到冒号后边的值,那你可以用字符串的indexOf方法加substr方法来实现。

var array = ['1001001:95', '1001002:100', '1001003:35', '1001004:37.5', '1001005:60', '1001006:100', '1001007:90', '1001008:140', '1001009:60', '1001010:90'];var number = '1001001';var value = '';for (var i = 0; i < array.length; i ++) { if(array[i].indexOf(number)!= -1){var index = array[i].indexOf(':');value = array[i].substr(index + 1, array[i].length); }}回答3:

数组遍历,针对每一个元素做一次 : 分割,将分割后的元素放到一个新数组里。

回答4:

我也不知道是不是应该这样搞啊,到时候取的话直接用key取就可以了

var a = ['1001001:95', '1001002:100', '1001003:35', '1001004:37.5', '1001005:60', '1001006:100', '1001007:90', '1001008:140', '1001009:60', '1001010:90'];function getResult(a,key){ var b = []; var c = {}; for(var i = 0;i < a.length; i++){b = a[i].split(':');c[b[0]] = b[1]; } return c[key];}console.log(getResult(a,1001001));

页面可以直接用

$scope.spo_high = getResult(arr,data[0]);回答5:

const array = ['1001001:95', '1001002:100', '1001003:35', '1001004:37.5', '1001005:60', '1001006:100', '1001007:90', '1001008:140', '1001009:60', '1001010:90'];let result = array.reduce((a,b)=>{ let [key,value] = b.split(’:’); a[key] = value; return a;},{});console.log(result[’1001001’]);// 95回答6:

data = data.split(’:’) if(data[0] == 1001001) {$scope.spo_low = data[1]; }else if(data[0] == 1001002){$scope.spo_high = data[1]; }else if(data[0] == 1001003) {$scope.temp_low = data[1]; }else if(data[0] == 1001004) {$scope.temp_high = data[1]; }else if(data[0] == 1001005) {$scope.plus_low = data[1]; }else if(data[0] == 1001006) {$scope.plus_high = data[1]; }else if(data[0] == 1001007) {$scope.sbp_low = data[1]; }else if(data[0] == 1001008) {$scope.sbp_high = data[1]; }else if(data[0] == 1001009) {$scope.dbp_low = data[1]; }else if(data[0] == 1001010) {$scope.dbp_high = data[1]; }

我这样编写各位大神看看这样有什么不妥?

标签: JavaScript
相关文章: