使用map返回一个空数组,而不是[0]零

时间:2018-10-09 15:58:02

标签: javascript arrays

我有一些工作代码,这些代码将包含一串单词并返回每个单词长度的数组。例如:

private let tableView: SelfSizedTableView = {
    let tv = SelfSizedTableView()
    tv.isScrollEnabled = false
    tv.translatesAutoresizingMaskIntoConstraints = false
    tv.tableFooterView = UIView()

    // explicitly set the row height and its estimated row height
    tv.estimatedRowHeight = 55 // ideally use 55 + edgeInsets.top + edgeInsets.bottom
    tv.rowHeight = UITableViewAutomaticDimension // automatic height based on content

    tv.register(TestTableViewCell.self, forCellReuseIdentifier: "cellId")
    return tv
}()

我的问题是,如果str =“”(空),它将返回[0]而不是[](空数组),这是我想要的。有谁知道如何更改代码以返回此代码?谢谢!

if view == nil {
    view = UIView(frame: .zero)
    view?.backgroundColor = .green
    view?.translatesAutoresizingMaskIntoConstraints = false

    contentView.addSubview(view!)

    // set priority on one of the constraints to 999:
    let heightConstraint = view!.heightAnchor.constraint(equalToConstant: 55)
    heightConstraint.priority = UILayoutPriority(rawValue: 999)
    // for reasoning behind this, read https://stackoverflow.com/q/44651241/2912282

    NSLayoutConstraint.activate([
        heightConstraint,
        view!.topAnchor.constraint(equalTo: contentView.topAnchor, constant: edgeInsets.top),
        view!.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -edgeInsets.bottom),
        view!.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: edgeInsets.left),
        view!.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -edgeInsets.right)
        ])
}

2 个答案:

答案 0 :(得分:5)

如果字符串等于''(空字符串),则可以返回一个空数组:

function count(str) {
  return (str === '') ? [] : str.split(' ').map(({length}) => length);
}

console.log(count('hello world'));
console.log(count(''));

答案 1 :(得分:3)

在末尾添加一个filter

const str = "";
const arr = str.split(' ');
console.log(arr.map(words => words.length).filter(count => count != 0));