从文本区域获取文本统计信息。
哪个更好?
这个?
function getStats() {
var text = textarea.value,
stats = {};
stats.chars = text.length;
stats.words = text.split(/\S+/g).length - 1;
stats.lines = text.replace(/[^\n]/g, "").length + 1;
return stats.lines + " lines, " + stats.words + " words, " + stats.chars + " chars";
}
还是这个?
function getStats() {
var text = textarea.value,
chars = text.length,
words = text.split(/\S+/g).length - 1,
lines = text.replace(/[^\n]/g, "").length + 1;
return lines + " lines, " + words + " words, " + chars + " chars";
}
最佳答案
第二个。
不是出于任何性能原因,而是您只是在不需要时声明一个 Javascript 对象。
创建一个对象来存储变量只有在您像这样使用它时才有意义:
function getStats() {
var text = textarea.value,
stats = {};
stats.chars = text.length;
stats.words = text.split(/\S+/g).length - 1;
stats.lines = text.replace(/[^\n]/g, "").length + 1;
return stats;
}
关于javascript - 从文本区域获取统计信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19589535/