示例:
var string = "abcde"; var array = string.split(""); // array = ["a", "b", "c", "d", "e"]此拆分功能的摊销运行时间是多少?另外,如何在javascript中查看此类内置函数的源代码?
What is the amortized running time of this split function? Also, how do I view source code of such built-in functions in javascript?
推荐答案使用空的定界符参数,split本质上等效于:
With an empty delimiter argument, split is essentially equivalent to:
var len = string.length; var result = Array(len) for (i = 0; i < len; i++) { result[i] = string[i]; }这是O(len).
使用定界符,它将变为O(string.length * delimiter.length),因为在循环的每个步骤中,它都必须测试delimiter是否匹配.
With a delimiter, it becomes O(string.length * delimiter.length), because at each step in the loop it has to test whether there's a match for delimiter.