数组随机排序

52 阅读2分钟

一、核心实现方法(基于substringslice

abcdefg是一个7个字符的字符串(索引从0开始:a(0)、b(1)、c(2)、d(3)、e(4)、f(5)、g(6)),efg对应索引4-6,可通过以下方法截取:

1. substring(startIndex, endIndex)

  • 语法:str.substring(开始索引, 结束索引)(结束索引不包含在内)。
  • 实现:
    const str = 'abcdefg';
    const result = str.substring(4, 7); // 从索引4开始,到索引7结束(不含7)
    console.log(result); // 'efg'
    
  • 特点:若startIndex大于endIndex,会自动交换位置(如substring(7,4)等效于substring(4,7))。

2. slice(startIndex, endIndex)

  • 语法:str.slice(开始索引, 结束索引)(与substring类似,但支持负数索引)。
  • 实现:
    const str = 'abcdefg';
    // 方法1:正数索引
    const result1 = str.slice(4, 7); // 'efg'
    // 方法2:负数索引(从末尾开始计算,-3表示倒数第3个字符)
    const result2 = str.slice(-3); // 'efg'(省略endIndex则截取到末尾)
    
  • 优势:支持负数索引(更灵活,尤其适合截取末尾固定长度的字符串)。

二、其他方法(substr不推荐)

substr(startIndex, length)也可实现,但已从Web标准中移除,不建议使用:

const str = 'abcdefg';
const result = str.substr(4, 3); // 从索引4开始,截取3个字符 → 'efg'

三、问题与

1. 问:substringslice的核心区别是什么?
    • 负数索引处理:slice支持负数(表示从末尾开始),substring会将负数转为0;
    • 索引顺序:substring会自动交换startend(若start > end),slice则返回空字符串。
2. 问:如果字符串长度不确定,如何截取最后3个字符?
  • :用slice的负数索引,无需计算具体长度:
    const str = 'abcdefg'; // 任意长度字符串
    const lastThree = str.slice(-3); // 始终截取最后3个字符 → 'efg'
    
3. 问:截取时需要注意哪些边界情况?
    • endIndex超过字符串长度,会自动截取到末尾(如str.slice(4, 10)仍返回'efg');
    • startIndex大于字符串长度,返回空字符串;
    • 空字符串或长度不足3的字符串,截取结果为实际长度(如'ab'截取最后3个字符返回'ab')。

话术

“截取abcdefg中的efg,核心是确定目标字符的索引范围(4-6):

  • substring(4,7)slice(4,7)均可实现,其中slice更灵活(支持负数索引);
  • 若字符串长度不确定,推荐slice(-3)直接截取最后3个字符,无需计算起始索引;
  • 实际开发中需注意边界情况(如字符串过短),确保代码健壮性。