小编sha*_*_00的帖子

javascript合并排序和递归

我试图了解 JavaScript 合并排序功能是如何工作的。我很难理解递归函数是如何工作的。这是代码:

const mergeSort = array => {
  if (array.length < 2) {
    //function stop here
    return array
  }

  const middle = Math.floor(array.length / 2);
  const leftSide = array.slice(0, middle);
  const rightSide = array.slice(middle, array.length);
  return merge(mergeSort(leftSide), mergeSort(rightSide))

};

const merge = (left, right) => {
  const result = [];

  while (left.length && right.length) {
    if (left[0] <= right[0]) {
      result.push(left.shift());
    } else {
      result.push(right.shift);
    }
  }

  while(left.length) result.push(left.shift());

  while(right.length) result.push(right.shift());

  return result;
}
mergeSort([5,3,8,10,4,1])
Run Code Online (Sandbox Code Playgroud)

javascript arrays sorting recursion mergesort

4
推荐指数
1
解决办法
3616
查看次数

在 componentDidUpdare 中 React setState 导致超出最大更新深度

我正进入(状态

错误:超出最大更新深度。当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况。React 限制嵌套更新的数量以防止无限循环。

但我读到的内容应该能够在 componentDidMount 中调用 setState 而不会出现错误。

class MyComponent extends Component {
constructor(props) {
    super(props);
    this.state = {
        matchtedProducts: [],
        products: [],
    }
}
async componentDidMount() {
    try {
        const products = await getProducts()
        this.setState({ products })
    } catch(err) {
        console.log(err)
    }
}

componentDidUpdate() {
    const productColor = this.props.size.trim().toLowerCase()
    const productSize = this.props.color.trim().toLowerCase()
    const matches = []

    this.state.products.map(product => {
        const title = product.title
        const titleSpliitet = title.split(',')

        let color = titleSpliitet[1].trim().toLowerCase()
        let …
Run Code Online (Sandbox Code Playgroud)

javascript setstate reactjs react-lifecycle

2
推荐指数
1
解决办法
1万
查看次数