'if condition'和'console.log'内部相等检查之间的区别

时间:2018-10-31 17:51:18

标签: javascript

我正在尝试一个代码段,对于console.log语句和条件语句中的空数组检查,结果是不同的。 关于为什么与众不同的帮助/想法? 预先感谢!

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define BUF_SIZE_WORDS 4096
#define BUF_SIZE_NUMBERS 256
#define MAX_WORDS 10

typedef struct tablestruct
{
    int val;
    char* text;
    struct tablestruct *next;
}
table;


// declare the hashing function that takes in the string to be hashed and the length of it
unsigned int hash(char *str, int length);

// // declare a linked list creation function
// lnode *createnode(char *str, htnode *hashtable);

// declare a hash table printing function
void print_ht(table *array[MAX_WORDS]);


int number_input();
int word_input(int num_words, table *array[MAX_WORDS]);
void empty_stdin();

int main(void)
{
    // call number_input() to ask user for number of words they'd like to store, save that in word_count
    int word_count = number_input();

    // create hash table
    table *array[MAX_WORDS];

    for (int j = 0; j < MAX_WORDS; j++)
    {
        array[j] = malloc(sizeof(table));
        array[j]->val = j;
    }

    // add some kind of a memory check?

    // PUT word_input inside the if statement to make sure it worked?
    // call word_input() and store the result in success
    int success = word_input(word_count, array);
    // if not successful:
    if (!success)
    {
        fputs ("some kind of problem with word_input\n", stderr);
        return 1;
    }

    // printf("\ncurrent address of the hash table: %p\n", &array[0]);

    printf("printing hash table: \n");

    print_ht(array);

    // REMEMBER TO FREE WHATEVER'S MALLOC'ED
}

int number_input(void)
{
    // a bunch of code is borrowed from David's answer here: https://stackoverflow.com/questions/52920852/why-is-the-following-code-not-allowing-me-to-get-user-input-with-fgets-yet-works?noredirect=1#comment92940817_52920852

    int num_words = 0,       /* number of words to enter */
        word_count_check = 0;          /* word count */

    char buffer[BUF_SIZE_NUMBERS] = "";    /* buffer of sufficient size for input */

    for (;;) /* loop continually until valid input of NUMBER OF WORDS USER WANTS TO ENTER or user cancels */
    {
        printf ("how many words would you like to enter? [1-%d]: ", MAX_WORDS);
        // check for cancellation of input
        if (!fgets (buffer, BUF_SIZE_NUMBERS, stdin))
        {
            fputs ("user canceled input\n", stderr);
            return 1;
        }

        // check if user simply hit enter w/o typing anything
        if(buffer[0] == '\n')
        {
            printf("please enter a value\n");
            continue;
        }

        size_t inlength = strlen(buffer);

        if (inlength && buffer[inlength - 1] == '\n')
        {
            // printf("hurray!\n");
            buffer[--inlength] = 0;
        }
        else if (inlength == BUF_SIZE_NUMBERS - 1) /* the line was too long */
        {
            printf("you've entered too many characters... please stick to a maximum of %i\n", BUF_SIZE_NUMBERS);
            empty_stdin();
            // continue;
        }

        // make sure user actually entered a proper int
        if (sscanf (buffer, "%d", &num_words) != 1) /* sscanf is used for conversion */
        {
            fputs ("invalid conversion to int; please provide valid input\n", stderr);
            continue;
        }

        // check if the number entered is out of range
        if (num_words < 1 || num_words > MAX_WORDS)
            fprintf (stderr, "%2d out of valid range.\n", num_words);
        else
            break; /*if the input has been validated, we can now break out of the for loop */
    }

    return(num_words);
}

int word_input(int num_words, table *array[MAX_WORDS])
{
    int word_count = 0;

    for(;;) /* loop until word_count == num_words is achieved */
    {
        // declare an array for storing input string
        char buffer[BUF_SIZE_WORDS];
        char valid_input[BUF_SIZE_WORDS];

        // prompt user for input
        printf("\nplease enter a string: ");

        // get input and check for CTRL+D
        if (!fgets(buffer, BUF_SIZE_WORDS, stdin))
        {
            fputs ("user canceled input\n", stderr);
            exit(1);
        }

         // check if user simply hit enter w/o typing anything
        if(buffer[0] == '\n')
        {
            printf("please enter a word that's more than 0 characters\n");
            // empty_stdin();
            continue;
        }

        size_t inlength = strlen(buffer);

        if (inlength && buffer[inlength - 1] == '\n')
        {
            buffer[--inlength] = 0;

            // get rid of trailing spaces using sscanf
            sscanf(buffer, "%s", valid_input);
            inlength = strlen(valid_input);

            printf("string length: %zu\n", inlength);

            // call the hash function to get the hash code
            int result = hash(&valid_input[0], inlength);

            table *newnode = malloc(sizeof(table));
            newnode->text = malloc(strlen(valid_input)+1);
            strcpy(newnode->text, valid_input);

            // confirm string has been stored
            printf("you've entered: %s\n", newnode->text);

            // attach the node to correct slot in the hash table -- ADD LINKED LIST FUNCTIONALITY HERE TO DEAL WITH COLLISIONS!
            array[result]->next = newnode;
            // printf("address of the current HT entry is: %p\n", newnode);

            // increment word count
            word_count++;
            printf("word_count = %i\n", word_count);

            if (word_count == num_words)
            {
                 printf("\nDONE!\n\n");
                 return word_count;
            }
        }
        // check if the user entered too many characters
        else if (inlength == BUF_SIZE_WORDS - 1) /* the line was too long */
        {
            printf("you've entered too many characters... please stick to a maximum of %i\n", BUF_SIZE_WORDS);
            empty_stdin();
        }
    }
    // return word_count;
}


/* helper function to remove any chars left in input buffer */
void empty_stdin()
{
    int c = getchar();
    while (c != '\n' && c != EOF)
        c = getchar();
}

// THIS HASH FUNCTION IS TOO BASIC AND NEEDS TO BE REPLACED WITH SOMETHING BETTER
unsigned int hash(char *str, int length)
{
    int sum = 0;
    for (int j = 0; j < length; j++)
    {
        sum += str[j];
    }
    printf("here's what the hashing function is returning: %i\n", (sum % MAX_WORDS));
    return sum % MAX_WORDS;
}

void print_ht(table *array[MAX_WORDS])
{
    // printf("address of the hash table inside print function: %p\n\n", array);

    table *cursor; // = malloc(sizeof(table));
    // add memory check

    for (int i = 0; i < MAX_WORDS; i++)
    {
        printf("[%i] -> ", i);
        cursor = array[i];
        if (cursor->next)
        {
            table *temp; //= malloc(sizeof(table));
            temp = cursor->next;

            printf("%s\n", temp->text);
            // free(temp);
        }
        else
        {
            printf("empty\n");
        }
    }
    // free(cursor);
}

4 个答案:

答案 0 :(得分:1)

您似乎正在遇到一个已知的JavaScript古怪。

“ []是真实的,但不是真实的”

问题不在您进行评估的地方,而是看起来似乎相同的两个评估实际上是不同的。

请参阅 https://github.com/denysdovhan/wtfjs#-is-truthy-but-not-true

答案 1 :(得分:0)

我的假设是,if / else块是其“真实”测试的一部分,它正在检查是否存在某些东西(不仅仅是真假)-其中直接的控制台打印结果是比较空值布尔值数组(可能为假)

let test = 'apple';
if( test ){
  console.log( 'if/else: ' + true );
}else{
  console.log( 'if/else: ' + false );
}

console.log( 'log: ' + ( test == true ) );

答案 2 :(得分:0)

这两个代码片段实际上在做不同的事情,因此结果也不同。

第一个以[]作为if语句的条件,将数组强制为布尔值。 (if很自然,仅适用于布尔值,如果JS不是给定的布尔值,JS将很乐意转换给定值。)这将产生true-JS中的所有对象都是“真实的”,这包括所有数组。

对于第二个片段,您使用的是“松散相等”运算符==-JS规范为此提供了一组规则,用于将值转换为其他类型,最终实现了两者之间的直接比较相同类型的值。您可能希望或希望,在这种情况下将非布尔值与truefalse进行比较会将非布尔值强制为布尔值-但这不会发生。规范说的是,首先将布尔值强制转换为数字值-导致1的{​​{1}}(和true的{​​{1}})。因此,它减少为0-在产生false结果之前将进行更多的转换。

关键是在第二种情况下不会发生向布尔值的转换。如果您认为这很愚蠢,那可能是对的。这有点麻烦,这也是许多指南告诉您不要在JS中使用[] == 1的原因之一。实际上,我实际上并不认同该建议(并且讨厌的短毛猫告诉我,在任何情况下都必须使用false)-但是您必须意识到一些危险。并且始终避免使用=======进行比较。

幸运的是,如果您想测试true是真实还是虚假,则可以使用一种非常简短且可以理解的方式来进行操作-您在此处的第一段代码中使用的方式是:false

答案 3 :(得分:-1)

[edit]因此,我的原始答案令人困惑,在整个互联网上,您在有关该主题的许多答案中都存在一些不一致之处;所以,让我再试一次:

第1部分:为什么与众不同

if([]) if([] == true)是不同的操作。如果您看到以下示例,则在执行相同的操作时将获得相同的结果。

//Output: false
if([] == true) {
    console.log(true);
} else{
    console.log(false);
}

//Output: false
console.log([] == true);

第2部分:又为何重要:令人困惑的地方

在JS中,以下是用于查看对象/变量是否存在的通用表达式:

var foo = "Hello World";
if (foo) ...

从设计的角度来看,此测试对于确定 foo 是否等于true或false并不重要,它是一种测试程序是否可以找到对象或变量 foo 。如果找到 foo ,则它将在“ then”条件下执行结果,否则将得到“ else”条件。因此,在这种情况下,它将foo转换为false(对于不存在)或true(对于存在)。因此,在这种情况下,字符串被简化为布尔值。

相反:

var foo = "Hello World";
if (foo == true) ...

通常试图找出 foo 的值是否实际等于true。在这种情况下,您将foo“ Hello World”的值与布尔值进行比较,因此,在这种情况下,“ Hello World”并不等于true。

就像foo一样,[]可以用多种方法求值。空数组仍然是一个对象;因此,在第一种情况下,它强制为true,因为它想知道是否可以找到[]。但是,[]也等于['']。所以现在想象一下:

if (['bar'] == 'bar') ...

在这种情况下,JS不会查看['bar']是否存在,而是将其视为包含单个值的对象,它可以将其转换为字符串'bar'。

所以:

if([]); // is true because it is an object test that evaluates as (1 === 1)

if([] == true) // is false because it is a string test that evaluates as ('' == 1) to (0 === 1)