例:在“hello,world” 里面是否有el
let str = "hello,world", str1 = 'l'
let idx=str.indexOf(str1)
if(idx!==-1){console.log('字符串'+str+'内存在'+str1+',下标位置为:'+idx)
} else {console.log('字符串'+str+'内未找到'+str1)
}
// 如果有多个时,会返回第一个字符(串)所在的位置
// 如果要找到最后一个,可以使用 lastIndexOf()
let arr = ["hello","world","china","beautiful"], obj = 'world'
let idx=arr.indexOf(obj)
if(idx!==-1){console.log('字符串'+arr+'内存在'+obj+',下标位置为:'+idx)
} else {console.log('字符串'+arr+'内未找到'+obj)
}
// 如果有多个时,会返回第一个字符(串)所在的位置
// 如果要找到最后一个,可以使用 lastIndexOf()
/*** 通过某个值找出其所在的item对象* @list 数组对象* @inKey 需要作为条件的key键* @inVal 需要作为条件的key值* @outVal 需要返回的结果的key键* 举例:在json中找id==2的name * inKey='id'* inVal='2'* outVal='name'* * let json = [{name: '张三',id:'1'},{name: '李斯',id:'2'},{name: '旺屋',id:'3'},
] **/
findItemFromKey = function (list, inKey, inVal, outKey) {if ((!list) || list.length == 0) {console.error('数组对象不能为空')return '';}if (!(list instanceof Array)) {console.error('数组对象必须是数组')return '';}if (inKey == undefined || inKey == null, inVal == undefined || inVal == null) { //此处可能会有0值console.error('被寻找键或被寻找值不能为空')return '';}let data = list.find((item) => {return item[inKey] == inVal})if (outKey) {return data ? data[outKey] : ''} else {return data ? data : ''}
}
let json = [{name: '张三',id:'1'},{name: '李斯',id:'2'},{name: '旺屋',id:'3'},
]
let out = findItemFromKey(json, 'id', 2)
console.log(out)//{ name: '李斯', id: '2' }
let out1 = findItemFromKey(json, 'id', 2,'name')
console.log(out1)//李斯
例:将hello,world内所有的l替换为#
let str = "hello,world"
str=str.replace(/l/gi, '#')
console.log(str)
// 注意,replace 不改变原来字符串,返回的是新的字符串,所以为了操作方便需要重新赋值,也可以直接返回得到的新值
例:将后台返回的如下数据,转为我们需要的label+value结构
let json = [{name: '张三',id:'1'},{name: '李斯',id:'2'},{name: '旺屋',id:'3'},
]
// 转换后的结果let json = [{label: '张三',value:'1'},{label: '李斯',value:'2'},{label: '旺屋',value:'3'},
]
let data = JSON.parse(JSON.stringify(json).replace(/"name"/g, '"label"'))
data = JSON.parse(JSON.stringify(data).replace(/"id"/g, '"value"'))
console.log(data)
// 注意:这种方法可以替换多层数据