数组或对象一些比较实用的方法

108 阅读1分钟

slice()

slice()方法返回一个索引和另一个索引之间的字符串,语法如下:

str.slice(beginIndex[, endIndex])

下面有三点需要注意:

  • beginIndex为负数,则将该值加上字符串长度后再进行计算(如果加上字符串的长度后还是负数,则从0开始截取)。
  • 如果beginIndex大于或等于字符串的长度,则slice()返回一个空字符串。
  • 如果endIndex省略,则将slice()字符提取到字符串的末尾。如果为负,它被视为strLength + endIndex其中strLength是字符串的长度。

以下是一些示例代码:

var str = 'abcdefghij';
console.log('(1, 2): '   + str.slice(1, 2));   // '(1, 2): b'
console.log('(-3, 2): '  + str.slice(-3, 2));  // '(-3, 2): '
console.log('(-3, 9): '  + str.slice(-3, 9));  // '(-3, 9): hi'
console.log('(-3): '     + str.slice(-3));     // '(-3): hij'
console.log('(-3,-1): ' + str.slice(-3,-1));     // '(-3,-1): hi'
console.log('(0,-1): '  + str.slice(0,-1));     // '(0,-1): abcdefghi'
console.log('(1): '      + str.slice(1));      // '(1): bcdefghij'
console.log('(-20, 2): ' + str.slice(-20, 2)); // '(-20, 2): ab'
console.log('(20): '     + str.slice(20));  // '(20): '
console.log('(20, 2): '  + str.slice(20, 2));  // '(20, 2): '

需求二:替换对象的键

data = {
       id: '11',
       name: '张三'
       }
var keyMap = {
       id: '序列',
       name: '姓名'
      }
var objs = Object.keys(data).reduce((newData, key) => {
      let newKey = keyMap[key] || key
      newData[newKey] = data[key]
      return newData
      }, {})
console.log(objs)//Object {姓名: "张三"序列: "11"}