用于编写 removeSuffix() 的最佳方法是什么

What is the best method to use to write removeSuffix()?

本文关键字:最佳 方法 是什么 removeSuffix 用于      更新时间:2023-09-26

我想写一个简单的单行方法,叫做removeSuffix()

以下是我的选择:

test.slice(0, test.length - len);

test.substring(0, test.length - len);

test.substr(0, test.length - len);

给定此测试用例,它们都做同样的事情:

len = 1; // length of the suffix to remove
test = "abcd" // test string

当前实现:

function removeSuffix(str, len){
    return str.slice(0, str.length - len);
}

切片呢 "abcd".slice(0,-1)

如果你想传递长度,让它像

var len = 2;    
"abcde".slice(0,-(len))