如何遍历字符串,每次向数组添加1个额外的字符

时间:2019-07-08 18:59:59

标签: javascript

我正在尝试使用JS遍历字符串值,同时将第一个字符和随后的字符添加到数组中。下一个字符再次重复此过程。

例如,如果我要输入ABCD,则数组将变成:

[A,AB,ABC,ABCD,B,BC,BCD,C,CD,D]

2 个答案:

答案 0 :(得分:0)

这将起作用:

//Reducer
const initialState = {
error: false,
fetching: false,
myData: []
}

export const getDataReducer = (state = initialState, action) => {

switch (action.type) {
    case ActionTypes.MyData.fetch.request:
        return { ...state,
              fetching: true,
              error: false,
              myData: initialState.myData
            }

    case ActionTypes.MyData.fetch.success:
        return {
            ...state,
            myData: action.payload
            fetching: false,
            error: false
        }

    case ActionTypes.MyData.fetch.error:

        return { 
              ...state,
              error: true,
              fetching: false
            }
        }

export const getError = (state) => get(state, 'myData.error', false);

        const mapStateToProps = (state) => {
          return getMyData(state);
        }

        export const getMyData = createSelector(
          [getClientId, getFetching, getError],
          (clientId, fetching, error) => {
            console.log("in selector:", fetching, error)
            const state = store.getState();
            const myData = getData(state);

            let hasErrorOrNoData = error ? error : myData.length === 0;

            hasErrorOrNoData = fetching ? false : hasErrorOrNoData;
            console.log("in selector hasErrorOrNoData:", hasErrorOrNoData)

            return {
              error,
              fetching,
              hasErrorOrNoData,
              myData
            }
          }
        )
        export const DataTable = ({
          error,
          fetching,
          hasErrorOrNoData,
          myData
        }) => {
          console.log("in component this gets called only once")
          return ( <
            componentX rows = {
              myData
            }
            fetching = {
              fetching
            }
            error = {
              hasErrorOrNoData
            }
            errorComponent = { < NoDataMessage
              isError = {
                error
              }
              />
            }
            />
          )
        }

答案 1 :(得分:0)

您可以将问题分解为两个小函数,第一个函数combination of a single word然后在single world参数的播放中substring的每个元素传递此函数。

const text = "ABCD";
const arrayOfCombination = [];

const combinationWord = word => [...word].map((el, index) => word.substring(0, index + 1));

[...text].forEach((el, index) => arrayOfCombination.push(combinationWord(text.substring(index, text.length))));

console.log(arrayOfCombination.flat())